<?php

namespace app\admins\controller;

class Admin extends Base
{
    // Curd复用
    use Curd;
    private $group;

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $this->model = $this->admin;
        $this->sort = ['id' => 'desc'];
        $this->rule = [
            'username|用户名' => 'require|chsDash|min:3|max:25|token|unique:admin', //验证令牌且值唯一
            'password|密码' => 'require|min:5',
            'realname|真实姓名' => 'require|chsAlpha',
            'status|状态' => 'require|in:0,1',
        ];

        if ($this->action == 'save') {
            $this->param['add_time'] = time();
        }
        if ($this->action == 'save_edit') {
            unset($this->param['username']);
            if (empty($this->param['password'])) {
                unset($this->param['password']);
            } else {
                $this->param['password'] = password_hash($this->param['password'], PASSWORD_DEFAULT);
            }
            $avatar = $this->param['avatar'];
            $avatar && $this->app->db->table('files')->where('path', $avatar)->update(['status' => 0]);
        }
        $this->group = $this->admin_group->field('id, title')->column('title', 'id');
        $this->app->view->assign('group', $this->group);
    }

    // 数据处理
    private function datas($datas)
    {
        $datas = $datas->map(function ($item) {
            $item['group_title'] = $this->group[$item['gid']];
            $item['avatar'] = $item['avatar'] ? '<img src="' . $item['avatar'] . '" style="width:50%;height:100%;display:inline-block;" />' : '';
            $item['lastlogin'] = date('Y-m-d H:i:s', $item['lastlogin']);
            $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
            return $item;
        });
        return $datas;
    }
}
